package net.jiastudy.biz.datasync.strategy.gxcm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.jiastudy.biz.datasync.DataSyncStrategy;
import net.jiastudy.biz.datasync.SyncUtil;
import net.jiastudy.biz.datasync.strategy.gxcm.bean.OrgBean;
import net.jiastudy.biz.datasync.strategy.gxcm.bean.TeacherBean;
import net.jiastudy.core.exception.ServiceException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("gxcmDataSyncStrategy")
public class GxcmDataSyncStrategyImpl implements DataSyncStrategy {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${gxcm.datacenter.url}")
    private String gxcmUrl;
    @Value("${gxcm.datacenter.applyId}")
    private String gxcmApplyId;
    @Value("${gxcm.datacenter.secretKey}")
    private String gxcmSecretKey;
    @Value("${gxcm.datacenter.teacher.serviceNum}")
    private String gxcmTeacherServiceNum;
    @Value("${gxcm.datacenter.org.serviceNum}")
    private String gxcmOrgServiceNum;

    @Resource
    private GxcmAsyncTaskService gxcmAsyncTaskService;

    @Override
    public boolean syncTeacher() {
        if (SyncUtil.getTeacherSyncBatchCount() > 0) {
            throw new ServiceException("已经有同步任务正在执行，请稍后再试！");
        }
        Map<String, OrgBean> orgMap = this.syncOrg();
        String body = this.fetchGxcmBody(gxcmUrl + "/getRest/jzgjbxx", gxcmTeacherServiceNum);
        logger.debug(body);
        JSONObject jsonObject = JSON.parseObject(body);
        if (!"200".equals(jsonObject.getString("status"))) {
            throw new ServiceException("调用数据中心教师信息同步接口失败:" + body);
        }
        List<TeacherBean> teacherBeans = jsonObject.getJSONObject("data").getJSONArray("Rows").toJavaList(TeacherBean.class);

        this.pageCreateTeacher(teacherBeans, 100, orgMap);
        return true;
    }

    private Map<String, OrgBean> syncOrg() {
        String body = fetchGxcmBody(gxcmUrl + "/getRest/zzjg",  gxcmOrgServiceNum);
        JSONObject jsonObject = JSON.parseObject(body);
        if (!"200".equals(jsonObject.getString("status"))) {
            throw new ServiceException("调用数据中心组织机构同步接口失败:" + body);
        }
        List<OrgBean> orgBeans = jsonObject.getJSONObject("data").getJSONArray("Rows").toJavaList(OrgBean.class);

        Map<String, OrgBean> beanMap = new HashMap<>();
        for (OrgBean orgBean : orgBeans) {
            beanMap.put(orgBean.getDm(), orgBean);
        }

        return beanMap;
    }

    private boolean pageCreateTeacher(List<TeacherBean> teachers, int pagesize, Map<String, OrgBean> orgMap) {
        int totalcount = teachers.size();
        int pagecount = 0;
        int m = totalcount % pagesize;
        if (m > 0) {
            pagecount = totalcount / pagesize + 1;
        } else {
            pagecount = totalcount / pagesize;
        }

        logger.info("一共有" + teachers.size() + "位老师需要同步,分" + pagecount + "次");
        SyncUtil.setTeacherSyncBatchCount(pagecount);
        for (int i = 1; i <= pagecount; i++) {
            List<TeacherBean> subList = null;
            if (m == 0) {
                subList = teachers.subList((i - 1) * pagesize, pagesize * (i));
            } else {
                if (i == pagecount) {
                    subList = teachers.subList((i - 1) * pagesize, totalcount);
                } else {
                    subList = teachers.subList((i - 1) * pagesize, pagesize * (i));
                }
            }
            if (null != subList) {
                logger.info("第" + i + "次异步处理，老师数" + subList.size());
                gxcmAsyncTaskService.createTeachers(subList, orgMap);
            }
        }
        return true;
    }

    private String fetchGxcmBody(String url, String serviceNum) {
        HttpClient httpClient=new DefaultHttpClient();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("page",1);
        jsonObject.put("pagesize", Integer.MAX_VALUE);
        StringEntity entity = new StringEntity(jsonObject.toString(), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        HttpPost method = new HttpPost(url);
        method.setEntity(entity);
        method.setHeader("secretKey", gxcmSecretKey);
        method.setHeader("serviceNum", serviceNum);
        method.setHeader("applyId", gxcmApplyId);

        HttpResponse result = null;
        String body = null;
        try {
            result = httpClient.execute(method);
            HttpEntity ret = result.getEntity();
            body = EntityUtils.toString(ret);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return body;
    }

    @Override
    public boolean syncDepts() {
        return false;
    }

    public static void main(String[] args) {
        DataSyncStrategy strategy = new GxcmDataSyncStrategyImpl();
    }
}
